package com.pactera.madp.cp.controller.sidebar.prod;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pactera.madp.admin.api.vo.SysFileVo;
import com.pactera.madp.common.core.util.R;
import com.pactera.madp.common.log.annotation.SysLog;
import com.pactera.madp.cp.api.dto.prod.UpdateIntroDTO;
import com.pactera.madp.cp.api.entity.WorkEmployeeEntity;
import com.pactera.madp.cp.api.entity.prod.ProdEntity;
import com.pactera.madp.cp.api.feign.RemoteDeptService;
import com.pactera.madp.cp.api.vo.prod.*;
import com.pactera.madp.cp.common.enums.ProductGroupEnum;
import com.pactera.madp.cp.common.util.sync.SyncUtils;
import com.pactera.madp.cp.config.SyncConfig;
import com.pactera.madp.cp.service.*;
import com.pactera.madp.cp.service.sync.SyncFundStdDataInfoHisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 华融湘江产品管理-侧边栏
 *
 * @author HuHao
 * @date 2022/3/16 9:31
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/prodwechat")
@Slf4j
@Api(value = "prodwechat", tags = "侧边栏产品管理")
public class SidebarProdController {

    private final ProdService prodService;
    private final IWorkEmployeeService workEmployeeService;
    private final RemoteDeptService remoteDeptService;
    private final ProdGroupService prodGroupService;
    private final SyncFundStdDataInfoHisService dataInfoHisService;
    private final SyncConfig syncConfig;

    @GetMapping("/fund-nav-tendency")
    @ApiOperation(value = "基金详情-净值趋势图")
    public R<List<ProdFundNavTendencyVo>> fundNavTendency(Integer id) {
        String code = prodService.getById(id).getCode();
        return R.ok(dataInfoHisService.fundNavTendency(code));
    }

    @GetMapping("/list")
    @ApiOperation(value = "查询金融小店产品分类列表")
    public R getProdTree() {
        return R.ok(prodGroupService.getProdGroupTree(1));
    }

    @GetMapping("/page-product")
    @ApiOperation(value = "查询产品")
    public R product(@RequestParam(required = false) Integer status, String wxUserId, Page page) {
        if (status != null) {
            if (!status.equals(0) && !status.equals(1))
                return R.failed("精选标识status不在取值范围{0, 1}内");
        }
//        WorkEmployeeEntity workEmployeeEntity = workEmployeeService.getOne(
//                Wrappers.<WorkEmployeeEntity>lambdaQuery()
//                        .eq(WorkEmployeeEntity::getWxUserId, wxUserId)
//        );
//        List<Integer> deptIds = (List<Integer>) remoteDeptService.getSelectedDepts(workEmployeeEntity.getMobile()).getData();
//        if (deptIds == null || deptIds.size() == 0)
//            return R.ok(new ArrayList<>());
        List<Integer> deptIds = new ArrayList<>();
        IPage<ProdEntity> prodEntities = prodService.product(status, deptIds, page);

        List<ProdDetailVo> prodDetailVos = new ArrayList<>();

        prodEntities.getRecords().forEach(prodEntity -> {
            ProdDetailVo vo = new ProdDetailVo();
            BeanUtil.copyProperties(prodEntity, vo);
            if (prodEntity.getType().equals(ProductGroupEnum.PRODUCT_FINANCE.getCode())) {
                String reserve1 = prodEntity.getReserve1();
                if (("1700".equals(reserve1) && prodEntity.getCode().startsWith("N")) || "1309".equals(reserve1)) {
                    vo.setProfolioType(1);
                } else {
                    vo.setProfolioType(0);
                }
                if ("1102".equals(reserve1) || "1303".equals(reserve1)) {
                    vo.setPrdTemplate("0");
                } else if ("1301".equals(reserve1) || "1401".equals(reserve1)) {
                    vo.setPrdTemplate("2");
                } else {
                    vo.setPrdTemplate("1");
                }

                if ("1301".equals(reserve1)) {
                    try {
                        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
                        Date date = sdf1.parse(prodEntity.getCycleDate().toString());
                        long cycleTime = date.getTime();
                        date = sdf1.parse(prodEntity.getCycleUpDate().toString());
                        long cycleUpdateTime = date.getTime();
                        long cycle = (cycleTime - cycleUpdateTime) / (24 * 60 * 60 * 1000);
                        //周期在30、90、180、365、540的前后15天，按照对应的值计算
                        if(cycle >= 15 && cycle <= 45) {
                            cycle = 30;
                        } else if(cycle >= 75 && cycle <= 105) {
                            cycle = 90;
                        } else if(cycle >= 165 && cycle <= 195) {
                            cycle = 180;
                        } else if(cycle >= 350 && cycle <= 380) {
                            cycle = 365;
                        } else if(cycle >= 525 && cycle <= 555) {
                            cycle = 540;
                        }
                        vo.setCycleDays(Integer.parseInt(String.valueOf(cycle)));
                    }catch(Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
                    Date date = sdf1.parse(prodEntity.getEndTime());
                    long endTime = date.getTime();
                    date = sdf1.parse(prodEntity.getStartTime());
                    long startTime = date.getTime();
                    long productDate = (endTime - startTime) / (24 * 60 * 60 * 1000);
                    vo.setProductDate(Integer.parseInt(String.valueOf(productDate)));
                } catch(Exception e) {
                    e.printStackTrace();
                }
                vo.setPlanVolRate(prodEntity.getModelComment());
            }
            if (prodEntity.getYearRate() != null) {
                vo.setYearRate(String.valueOf(prodEntity.getYearRate()));
            }
            if (prodEntity.getNav() != null) {
                vo.setNav(String.valueOf(prodEntity.getNav()));
            }
            if (prodEntity.getIncomeUnit() != null) {
                vo.setIncomeUnit(String.valueOf(prodEntity.getIncomeUnit()));
            }
            prodDetailVos.add(vo);
        });
        IPage<ProdDetailVo> prodDetailVoPage = new Page<>();
        BeanUtil.copyProperties(prodEntities, prodDetailVoPage);
        prodDetailVoPage.setRecords(prodDetailVos);
        return R.ok(prodDetailVoPage);
    }

    @GetMapping("/page-other")
    @ApiOperation(value = "查询其他产品")
    public R other(@RequestParam(required = false) Integer status, String wxUserId, Integer type, Page page) {
        if (status != null) {
            if (!status.equals(0) && !status.equals(1))
                return R.failed("精选标识status不在取值范围{0, 1}内");
        }
        if (!(type != null && (
                type.equals(ProductGroupEnum.ACTIVITY.getCode())
                        || type.equals(ProductGroupEnum.LOAN.getCode())
                        || type.equals(ProductGroupEnum.CREDITCARD.getCode())
        )))
            return R.failed("产品类型type不在取值范围{2-活动, 4-贷款, 5-信用卡}内");
        WorkEmployeeEntity workEmployeeEntity = workEmployeeService.getOne(
                Wrappers.<WorkEmployeeEntity>lambdaQuery()
                        .eq(WorkEmployeeEntity::getWxUserId, wxUserId)
        );
        List<Integer> deptIds = (List<Integer>) remoteDeptService.getSelectedDepts(workEmployeeEntity.getMobile()).getData();
        if (deptIds == null || deptIds.size() == 0)
            return R.ok(new ArrayList<>());
        IPage<ProdEntity> prodEntities = prodService.other(status, type, deptIds, page);

        return R.ok(prodEntities);
    }

    // 最初设计为理财/基金更多的接口 后来理财-更多单开了接口
    @GetMapping("/page-product-more")
    @ApiOperation(value = "更多-理财/基金")
    public R more(String searchStr, Integer riskLevel, String prdAttr, Integer status, String wxUserId, Integer type, Page page) {
        if (status != null) {
            if (!status.equals(0) && !status.equals(1))
                return R.failed("精选标识status不在取值范围{0, 1}内");
        }
        if (!(type != null && (
                type.equals(ProductGroupEnum.PRODUCT_FINANCE.getCode())
                        || type.equals(ProductGroupEnum.PRODUCT_FUND.getCode())
        )))
            return R.failed("产品类型type不在取值范围{11-理财, 12-基金}内");
        IPage<ProdEntity> prodEntities = prodService.other1(searchStr, riskLevel, prdAttr, status, type, page);
        List<ProdFinanceDetailVo> prodFinanceDetailVos = new ArrayList<>();
        if (type.equals(ProductGroupEnum.PRODUCT_FINANCE.getCode())) {
            prodEntities.getRecords().forEach(prodEntity -> {
                ProdFinanceDetailVo vo = new ProdFinanceDetailVo();
                BeanUtil.copyProperties(prodEntity, vo);
                String reserve1 = prodEntity.getReserve1();
                if (("1700".equals(reserve1) && prodEntity.getCode().startsWith("N")) || "1309".equals(reserve1)) {
                    vo.setProfolioType(1);
                } else {
                    vo.setProfolioType(0);
                }
                if ("1102".equals(reserve1) || "1303".equals(reserve1)) {
                    vo.setPrdTemplate("0");
                } else if ("1301".equals(reserve1) || "1401".equals(reserve1)) {
                    vo.setPrdTemplate("2");
                } else {
                    vo.setPrdTemplate("1");
                }

                if ("1301".equals(reserve1)) {
                    try {
                        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
                        Date date = sdf1.parse(prodEntity.getCycleDate().toString());
                        long cycleTime = date.getTime();
                        date = sdf1.parse(prodEntity.getCycleUpDate().toString());
                        long cycleUpdateTime = date.getTime();
                        long cycle = (cycleTime - cycleUpdateTime) / (24 * 60 * 60 * 1000);
                        //周期在30、90、180、365、540的前后15天，按照对应的值计算
                        if(cycle >= 15 && cycle <= 45) {
                            cycle = 30;
                        } else if(cycle >= 75 && cycle <= 105) {
                            cycle = 90;
                        } else if(cycle >= 165 && cycle <= 195) {
                            cycle = 180;
                        } else if(cycle >= 350 && cycle <= 380) {
                            cycle = 365;
                        } else if(cycle >= 525 && cycle <= 555) {
                            cycle = 540;
                        }
                        vo.setCycleDays(Integer.parseInt(String.valueOf(cycle)));
                    }catch(Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
                    Date date = sdf1.parse(prodEntity.getEndTime());
                    long endTime = date.getTime();
                    date = sdf1.parse(prodEntity.getStartTime());
                    long startTime = date.getTime();
                    long productDate = (endTime - startTime) / (24 * 60 * 60 * 1000);
                    vo.setProductDate(Integer.parseInt(String.valueOf(productDate)));
                } catch(Exception e) {
                    e.printStackTrace();
                }
                vo.setPlanVolRate(prodEntity.getModelComment());

                String prdAddress = prodEntity.getProductAddress();
                vo.setProductAddress(prdAddress);
                String prdStatus = prodEntity.getPrdStatus();
                String purchaseType = "1";
                Date now = new Date();
                if ("0".equals(prdStatus)) {
                    if ("0".equals(vo.getPrdTemplate())) {
                        purchaseType = "1";
                    } else if ("1".equals(vo.getPrdTemplate())) {
                        purchaseType = "0";
                        Date investStartDate = parse(vo.getInvestDateS(), prodEntity.getOpenTime());
                        Date investEndDate = parse(vo.getInvestDateE(), prodEntity.getCloseTime());
                        if (now.before(investStartDate)) {
                            purchaseType = "2";
                        } else if (now.after(investEndDate)) {
                            purchaseType = "1";
                        }
                    } else if ("2".equals(vo.getPrdTemplate())) {
                        purchaseType = "0";
                        if (null == vo.getInvestDateS() || "".equals(vo.getInvestDateS())) {
                            purchaseType = "1";
                        } else {
                            purchaseType = "3";
                        }
                    } else {
                        purchaseType = "1";
                    }
                } else if ("1".equals(prdStatus)) {
                    if ("0".equals(vo.getPrdTemplate())) {
                        purchaseType = "0";
                        Date raiseStartDate = parse(vo.getRaiseDateS(), prodEntity.getOpenTime());
                        Date raiseEndDate = parse(vo.getRaiseDateE(), prodEntity.getCloseTime());
                        if (now.before(raiseStartDate)) {
                            purchaseType = "2";
                        } else if (now.after(raiseEndDate)) {
                            purchaseType = "1";
                        }
                    } else if ("1".equals(vo.getPrdTemplate())) {
                        purchaseType = "0";
                        Date raiseStartDate = parse(vo.getRaiseDateS(), prodEntity.getOpenTime());
                        Date raiseEndDate = parse(vo.getRaiseDateE(), prodEntity.getCloseTime());
                        if (now.before(raiseStartDate) || now.after(raiseEndDate)) {
                            purchaseType = "1";
                        }
                    } else if ("2".equals(vo.getPrdTemplate())) {
                        purchaseType = "0";
                        try {
                            Date raiseStartDate = parse(vo.getRaiseDateS(), prodEntity.getOpenTime());
                            Date raiseEndDate = parse(vo.getRaiseDateE(), prodEntity.getCloseTime());
                            if (now.before(raiseStartDate)) {
                                purchaseType = "2";
                            } else if (now.after(raiseEndDate)) {
                                purchaseType = "1";
                            }
                        } catch (Throwable throwable) {
                            purchaseType = "1";
                        }
                    } else {
                        purchaseType = "1";
                    }
                }
                if ("0".equals(purchaseType) && (prdAddress == null || "".equals(prdAddress))) {
                    purchaseType = "2";
                }
                if ("1309".equals(reserve1) && ("0".equals(prdStatus) || "1".equals(prdStatus))) {
                    purchaseType = "0";
                    if (prdAddress == null || "".equals(prdAddress)) {
                        purchaseType = "2";
                    }
                }
                vo.setPurchaseType(purchaseType);
                prodFinanceDetailVos.add(vo);
            });
            IPage<ProdFinanceDetailVo> prodFinanceDetailVoPage = new Page<>();
            BeanUtil.copyProperties(prodEntities, prodFinanceDetailVoPage);
            prodFinanceDetailVoPage.setRecords(prodFinanceDetailVos);
            return R.ok(prodFinanceDetailVoPage);
        }
        return R.ok(prodEntities);
    }

    @GetMapping("/page-product-more-finance")
    @ApiOperation(value = "更多-理财")
    public R list(@RequestParam(required = false) Integer status, String wxUserId) {
        if (status != null) {
            if (!status.equals(0) && !status.equals(1))
                return R.failed("精选标识status不在取值范围{0, 1}内");
        }
        List<ProdEntity> prodEntities = prodService.otherFinance(status);

        List<ProdFinanceDetailVo> prodFinanceDetailVos = new ArrayList<>();
        prodEntities.forEach(prodEntity -> {
            ProdFinanceDetailVo vo = new ProdFinanceDetailVo();
            BeanUtil.copyProperties(prodEntity, vo);
            String reserve1 = prodEntity.getReserve1();
            if (("1700".equals(reserve1) && prodEntity.getCode().startsWith("N")) || "1309".equals(reserve1)) {
                vo.setProfolioType(1);
            } else {
                vo.setProfolioType(0);
            }
            if ("1102".equals(reserve1) || "1303".equals(reserve1)) {
                vo.setPrdTemplate("0");
            } else if ("1301".equals(reserve1) || "1401".equals(reserve1)) {
                vo.setPrdTemplate("2");
            } else {
                vo.setPrdTemplate("1");
            }

            if ("1301".equals(reserve1)) {
                try {
                    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
                    Date date = sdf1.parse(prodEntity.getCycleDate().toString());
                    long cycleTime = date.getTime();
                    date = sdf1.parse(prodEntity.getCycleUpDate().toString());
                    long cycleUpdateTime = date.getTime();
                    long cycle = (cycleTime - cycleUpdateTime) / (24 * 60 * 60 * 1000);
                    //周期在30、90、180、365、540的前后15天，按照对应的值计算
                    if(cycle >= 15 && cycle <= 45) {
                        cycle = 30;
                    } else if(cycle >= 75 && cycle <= 105) {
                        cycle = 90;
                    } else if(cycle >= 165 && cycle <= 195) {
                        cycle = 180;
                    } else if(cycle >= 350 && cycle <= 380) {
                        cycle = 365;
                    } else if(cycle >= 525 && cycle <= 555) {
                        cycle = 540;
                    }
                    vo.setCycleDays(Integer.parseInt(String.valueOf(cycle)));
                }catch(Exception e) {
                    e.printStackTrace();
                }
            }
            try {
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
                Date date = sdf1.parse(prodEntity.getEndTime());
                long endTime = date.getTime();
                date = sdf1.parse(prodEntity.getStartTime());
                long startTime = date.getTime();
                long productDate = (endTime - startTime) / (24 * 60 * 60 * 1000);
                vo.setProductDate(Integer.parseInt(String.valueOf(productDate)));
            } catch(Exception e) {
                e.printStackTrace();
            }
            vo.setPlanVolRate(prodEntity.getModelComment());

            String prdAddress = prodEntity.getProductAddress();
            vo.setProductAddress(prdAddress);
            String prdStatus = prodEntity.getPrdStatus();
            String purchaseType = "1";
            Date now = new Date();
            if ("0".equals(prdStatus)) {
                if ("0".equals(vo.getPrdTemplate())) {
                    purchaseType = "1";
                } else if ("1".equals(vo.getPrdTemplate())) {
                    purchaseType = "0";
                    Date investStartDate = parse(vo.getInvestDateS(), prodEntity.getOpenTime());
                    Date investEndDate = parse(vo.getInvestDateE(), prodEntity.getCloseTime());
                    if (now.before(investStartDate)) {
                        purchaseType = "2";
                    } else if (now.after(investEndDate)) {
                        purchaseType = "1";
                    }
                } else if ("2".equals(vo.getPrdTemplate())) {
                    purchaseType = "0";
                    if (null == vo.getInvestDateS() || "".equals(vo.getInvestDateS())) {
                        purchaseType = "1";
                    } else {
                        purchaseType = "3";
                    }
                } else {
                    purchaseType = "1";
                }
            } else if ("1".equals(prdStatus)) {
                if ("0".equals(vo.getPrdTemplate())) {
                    purchaseType = "0";
                    Date raiseStartDate = parse(vo.getRaiseDateS(), prodEntity.getOpenTime());
                    Date raiseEndDate = parse(vo.getRaiseDateE(), prodEntity.getCloseTime());
                    if (now.before(raiseStartDate)) {
                        purchaseType = "2";
                    } else if (now.after(raiseEndDate)) {
                        purchaseType = "1";
                    }
                } else if ("1".equals(vo.getPrdTemplate())) {
                    purchaseType = "0";
                    Date raiseStartDate = parse(vo.getRaiseDateS(), prodEntity.getOpenTime());
                    Date raiseEndDate = parse(vo.getRaiseDateE(), prodEntity.getCloseTime());
                    if (now.before(raiseStartDate) || now.after(raiseEndDate)) {
                        purchaseType = "1";
                    }
                } else if ("2".equals(vo.getPrdTemplate())) {
                    purchaseType = "0";
                    try {
                        Date raiseStartDate = parse(vo.getRaiseDateS(), prodEntity.getOpenTime());
                        Date raiseEndDate = parse(vo.getRaiseDateE(), prodEntity.getCloseTime());
                        if (now.before(raiseStartDate)) {
                            purchaseType = "2";
                        } else if (now.after(raiseEndDate)) {
                            purchaseType = "1";
                        }
                    } catch (Throwable throwable) {
                        purchaseType = "1";
                    }
                } else {
                    purchaseType = "1";
                }
            }
            if ("0".equals(purchaseType) && (prdAddress == null || "".equals(prdAddress))) {
                purchaseType = "2";
            }
            if ("1309".equals(reserve1) && ("0".equals(prdStatus) || "1".equals(prdStatus))) {
                purchaseType = "0";
                if (prdAddress == null || "".equals(prdAddress)) {
                    purchaseType = "2";
                }
            }
            vo.setPurchaseType(purchaseType);
            if (!"1".equals(vo.getPurchaseType())) {
                prodFinanceDetailVos.add(vo);
            }
        });
        return R.ok(prodFinanceDetailVos);
    }

    @GetMapping("/deposit-list")
    @ApiOperation(value = "查询存款列表")
    public R getDeposits(Integer type) {
        return R.ok(prodService.getDeposits(type));
    }

    @GetMapping("/deposits")
    @ApiOperation(value = "查询存款汇总列表")
    public R<List<ProdDepositVo>> deposits() {
        return R.ok(prodService.deposits());
    }

    @GetMapping("/fund-details")
    @ApiOperation(value = "查询基金详情")
    public R fundDetails(Integer id) {
        ProdEntity prodEntity = prodService.getById(id);
        ProdFundDetailVo vo = new ProdFundDetailVo();
        BeanUtil.copyProperties(prodEntity, vo);
        String prdCode = vo.getCode();
        // 文件目录检测
        String destDir = syncConfig.getFundOutlineNewPath();
        boolean flag = SyncUtils.checkDir(destDir, true);
        if (!flag) {
            log.debug("基金概要文件目录{}不存在", destDir);
        } else {
            List<String> fileNames = FileUtil.listFileNames(destDir);
            inner:
            for (String fileName : fileNames) {
                // 产品概要文件名以CN_开头
                if (!fileName.startsWith("CN_")) {
                    continue inner;
                }
                if (fileName.contains(prdCode)) {
                    String[] splits = fileName.split("_");
                    // 产品概要文件包含9个要素
                    if (splits.length != 9) {
                        continue inner;
                    }
                    // 第6个要素对应基金编码
                    if (splits[5].equals(prdCode)) {
                        String url = syncConfig.getFundOutlineSidebarPath() + File.separator + fileName;
                        url = url.replaceAll("\\\\", "/");
                        vo.setUrl(url);
                    }
                }
            }
        }
        return R.ok(vo);
    }

    @GetMapping("/finance-details")
    @ApiOperation(value = "查询理财详情")
    public R financeDetails(Integer id) {
        ProdEntity prodEntity = prodService.getById(id);
        ProdFinanceDetailVo vo = new ProdFinanceDetailVo();
        BeanUtil.copyProperties(prodEntity, vo);
        String reserve1 = prodEntity.getReserve1();
        if (("1700".equals(reserve1) && prodEntity.getCode().startsWith("N")) || "1309".equals(reserve1)) {
            vo.setProfolioType(1);
        } else {
            vo.setProfolioType(0);
        }
        if ("1102".equals(reserve1) || "1303".equals(reserve1)) {
            vo.setPrdTemplate("0");
        } else if ("1301".equals(reserve1) || "1401".equals(reserve1)) {
            vo.setPrdTemplate("2");
        } else {
            vo.setPrdTemplate("1");
        }

        if ("1301".equals(reserve1)) {
            try {
                SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
                Date date = sdf1.parse(prodEntity.getCycleDate().toString());
                long cycleTime = date.getTime();
                date = sdf1.parse(prodEntity.getCycleUpDate().toString());
                long cycleUpdateTime = date.getTime();
                long cycle = (cycleTime - cycleUpdateTime) / (24 * 60 * 60 * 1000);
                //周期在30、90、180、365、540的前后15天，按照对应的值计算
                if(cycle >= 15 && cycle <= 45) {
                    cycle = 30;
                } else if(cycle >= 75 && cycle <= 105) {
                    cycle = 90;
                } else if(cycle >= 165 && cycle <= 195) {
                    cycle = 180;
                } else if(cycle >= 350 && cycle <= 380) {
                    cycle = 365;
                } else if(cycle >= 525 && cycle <= 555) {
                    cycle = 540;
                }
                vo.setCycleDays(Integer.parseInt(String.valueOf(cycle)));
            }catch(Exception e) {
                e.printStackTrace();
            }
        }
        try {
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
            Date date = sdf1.parse(prodEntity.getEndTime());
            long endTime = date.getTime();
            date = sdf1.parse(prodEntity.getStartTime());
            long startTime = date.getTime();
            long productDate = (endTime - startTime) / (24 * 60 * 60 * 1000);
            vo.setProductDate(Integer.parseInt(String.valueOf(productDate)));
        } catch(Exception e) {
            e.printStackTrace();
        }

        vo.setPlanVolRate(prodEntity.getModelComment());
        vo.setRaiseDateS(prodEntity.getIpoStartDate());
        vo.setRaiseDateE(prodEntity.getIpoEndDate());
        vo.setInvestDateS(prodEntity.getStartTime());
        vo.setInvestDateE(prodEntity.getEndTime());

        String prdAddress = prodEntity.getProductAddress();
        vo.setProductAddress(prdAddress);
        String prdStatus = prodEntity.getPrdStatus();
        String purchaseType = "1";
        Date now = new Date();
        if ("0".equals(prdStatus)) {
            if ("0".equals(vo.getPrdTemplate())) {
                purchaseType = "1";
            } else if ("1".equals(vo.getPrdTemplate())) {
                purchaseType = "0";
                Date investStartDate = parse(vo.getInvestDateS(), prodEntity.getOpenTime());
                Date investEndDate = parse(vo.getInvestDateE(), prodEntity.getCloseTime());
                if (now.before(investStartDate)) {
                    purchaseType = "2";
                } else if (now.after(investEndDate)) {
                    purchaseType = "1";
                }
            } else if ("2".equals(vo.getPrdTemplate())) {
                purchaseType = "0";
                if (null == vo.getInvestDateS() || "".equals(vo.getInvestDateS())) {
                    purchaseType = "1";
                } else {
                    purchaseType = "3";
                }
            } else {
                purchaseType = "1";
            }
        } else if ("1".equals(prdStatus)) {
            if ("0".equals(vo.getPrdTemplate())) {
                purchaseType = "0";
                Date raiseStartDate = parse(vo.getRaiseDateS(), prodEntity.getOpenTime());
                Date raiseEndDate = parse(vo.getRaiseDateE(), prodEntity.getCloseTime());
                if (now.before(raiseStartDate)) {
                    purchaseType = "2";
                } else if (now.after(raiseEndDate)) {
                    purchaseType = "1";
                }
            } else if ("1".equals(vo.getPrdTemplate())) {
                purchaseType = "0";
                Date raiseStartDate = parse(vo.getRaiseDateS(), prodEntity.getOpenTime());
                Date raiseEndDate = parse(vo.getRaiseDateE(), prodEntity.getCloseTime());
                if (now.before(raiseStartDate) || now.after(raiseEndDate)) {
                    purchaseType = "1";
                }
            } else if ("2".equals(vo.getPrdTemplate())) {
                purchaseType = "0";
                try {
                    Date raiseStartDate = parse(vo.getRaiseDateS(), prodEntity.getOpenTime());
                    Date raiseEndDate = parse(vo.getRaiseDateE(), prodEntity.getCloseTime());
                    if (now.before(raiseStartDate)) {
                        purchaseType = "2";
                    } else if (now.after(raiseEndDate)) {
                        purchaseType = "1";
                    }
                } catch (Throwable throwable) {
                    purchaseType = "1";
                }
            } else {
                purchaseType = "1";
            }
        }
        if ("0".equals(purchaseType) && (prdAddress == null || "".equals(prdAddress))) {
            purchaseType = "2";
        }
        if ("1309".equals(reserve1) && ("0".equals(prdStatus) || "1".equals(prdStatus))) {
            purchaseType = "0";
            if (prdAddress == null || "".equals(prdAddress)) {
                purchaseType = "2";
            }
        }
        vo.setPurchaseType(purchaseType);
        return R.ok(vo);
    }

    private Date parse(String date, Integer time) {
        if (time == null) {
            time = 0;
        }
        String timeStr = String.format("%06d", time);
        if (date == null) {
            date = "0000-00-00";
        }
        String dateStr = date.substring(0, 10);
        String dateTime = dateStr + timeStr;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-ddHHmmss");
        try {
            return sdf.parse(dateTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    @GetMapping("/details")
    @ApiOperation(value = "查询其他产品详情")
    public R details(Integer id) {
        return R.ok(prodService.getById(id));
    }


    @GetMapping("/manager-details")
    @ApiOperation(value = "查询经理详细信息")
    public R<BusinessCardVO> getCustomerManagerDetails(@RequestParam(name = "wxUserId") String wxUserId) {
        return R.ok(prodService.getCustomerManagerDetails(wxUserId));
    }

    @SysLog("编辑经理介绍信息")
    @PostMapping("/edit-introduction")
    @ApiOperation(value = "编辑经理介绍信息")
    public R editIntroduction(@RequestBody UpdateIntroDTO dto) {
        return R.ok(prodService.editIntroduction(dto));
    }

    @SysLog("通过mediaId从企业微信获取头像并保存至本地")
    @PostMapping("/manager-avatar-upload")
    @ApiOperation(value = "通过mediaId从企业微信获取头像并保存至本地")
    public R<SysFileVo> managerAvatarUpload(@RequestParam(name = "wxUserId") String wxUserId, @RequestParam(name = "mediaId") String mediaId) {
        return prodService.managerAvatarUpload(wxUserId,mediaId);
    }

    @GetMapping("/sync")
    @ApiOperation(value = "sync")
    public R sync(Integer synType) {
        return R.ok(prodService.syn(synType));
    }

    /*@Autowired
    private RemoteDeptService deptService;

    @GetMapping("/remote/getAllZhLine")
    R getAllZhLine() {
        List<Integer> zhDeptId = deptService.getAllZhLine();
        return R.ok(zhDeptId);
    }*/

}
